# -*- coding: utf-8 -*-
# Copyright 2017 Jarvis (www.odoomod.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import sys
from odoo import models, fields, api
from odoo.exceptions import ValidationError
from ..lib import pycnamount
import json
import logging
_logger = logging.getLogger(__name__)


class AccountMove(models.Model):
    _inherit = 'account.move'

    post_uid = fields.Many2one('res.users', '记账人', readony=True, copy=False)
    approval_uid = fields.Many2one(
        'res.users', '审核人', readony=True, copy=False)
    cashier_uid = fields.Many2one('res.users', '出纳', readony=True, copy=False)
    amount_chinese = fields.Char(
        string="大写合计", compute='_compute_amount_chinese')
    to_check = fields.Boolean('已审核', readonly=True, default=False, copy=False)
    attachment_num = fields.Integer("附件", copy=False, default=1)

    debit_sum = fields.Monetary(default=0.0, compute='_compute_sum')
    credit_sum = fields.Monetary(default=0.0, compute='_compute_sum')

    table_diff_size = fields.Integer(compute='_compute_table_diff_size')

    tag_text = fields.Text(string='备注', default="", copy=False)

    custom_name = fields.Char(string="自定义凭证号")

    @api.multi
    def _compute_sum(self):
        for move in self:
            debit_sum = 0
            credit_sum = 0
            for line in move.line_ids:
                debit_sum += line.debit
                credit_sum += line.credit
            move.debit_sum = debit_sum
            move.credit_sum = credit_sum

    @api.multi
    def _compute_amount_chinese(self):
        for move in self:
            # debit = 0
            # credit = 0
            # for line in move.line_ids:
            #     debit += line.debit
            #     credit += line.credit
            # move.amount_chinese = pycnamount.amount2cn(
            #     debit if debit > 0 else credit, big=True)
            _logger.info(move.amount)
            move.amount_chinese = pycnamount.amount2cn(
                move.amount, big=True)

    @api.multi
    def post(self, invoice=False):
        for move in self:
            if move.approval_uid.id == False and self.env.user.has_group(
                    'odoo12_account.group_post_after_approval'):
                _logger.info('no post')
                return
                # raise ValidationError('凭证需审核才可记账')
            _logger.info('post')
            super(AccountMove, move).post(invoice)
            move.write({'post_uid': self.env.uid})

    @api.multi
    def button_approval(self):
        for move in self:
            if move.state != 'posted':
                if move.approval_uid.id == False:
                    if move.create_uid.id == self.env.uid and self.env.user.has_group(
                            'odoo12_account.group_same_user_approval') != True:
                        raise ValidationError('制单人和审核人不能相同')
                    move.write(
                        {'approval_uid': self.env.uid, 'to_check': True})
                else:
                    move.write({'approval_uid': False, 'to_check': False})

    @api.multi
    def button_cashier(self):
        for move in self:
            if move.state != 'posted':
                if move.cashier_uid:
                    move.write({'cashier_uid': False})
                else:
                    move.write({'cashier_uid': self.env.uid})

    @api.multi
    def _compute_table_diff_size(self):
        max_size = int(self.env['ir.config_parameter'].sudo().get_param(
            'odoo12_account.table_diff_size'))
        for move in self:
            rows = len(move.line_ids)
            diff = max_size - rows
            if diff > 0:
                move.table_diff_size = diff
            else:
                move.table_diff_size = 0

    @api.multi
    def button_cancel(self):
        for move in self:
            _logger.info('button_cancel')
            _logger.info(move.state)
            if move.state == 'posted':
                _logger.info('change')
                # move.state = 'draft'
                move.write({'state': 'draft'})

    @api.multi
    @api.onchange('line_ids')
    def compute_tag_text(self):
        for move in self:
            tem_str = ''
            for aml in move.line_ids:
                if(aml.name):
                    if(aml.name in tem_str):
                        pass
                    else:
                        tem_str = tem_str + aml.name + ','
            move.tag_text = tem_str[0:30]

    @api.model
    def create(self, vals):
        tem_str = ''
        # _logger.info(vals)
        if('line_ids' in vals):
            for line in vals['line_ids']:
                if line[2]['name']:
                    if line[2]['name'] in tem_str:
                        pass
                    else:
                        tem_str = tem_str + line[2]['name'] + ','
            vals['tag_text'] = tem_str[0:30]
        res = super(AccountMove, self).create(vals)
        return res
